/**
 * 
 */
package io.potato.core.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * 加密算法
 * @author timl
 *
 */
public class Hashs {
	
	/**
	 * 加密算法
	 */
	private static String hashAlgorithmName = "SHA-256";
	
	/**
	 * 加密次数
	 */
	private static int hashIterations = 13;
	
	private static final String SOURCE = "0123456789";
	
	/**
	 * 加密字符串
	 * @param str  要加密的字符
	 * @param salt 盐
	 * @return  加密后的字符串
	 */
	public static String computeHash(String str) {
		return digest(str);
	}
	
	public static boolean hashEquals(String hashedStr, String clearText) {
		return hashedStr.equals(computeHash(clearText));
	}
	
	public static String digest(String str) {
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("SHA");
			messageDigest.update(salt);
			return Base64.encode(messageDigest.digest(str.getBytes()));
		} catch (NoSuchAlgorithmException ex) {
			throw new UnsupportedOperationException(ex.toString());
		}
	}
	
	/**
	 * 返回加密算法
	 * @return  加密算法
	 */
	public static String getHashAlgorithmName() {
		return hashAlgorithmName;
	}
	
	/**
	 * 返回加密次数
	 * @return  加密次数
	 */
	public static int getHashIterations() {
		return hashIterations;
	}
	
	/**
	 * 生成随机盐值
	 * @return  返回盐值
	 */
	public static String randomSalt() {
		return randomDigit(8);
	}
	
	public static String randomDigit(int digits) {
		Random rand = new Random();
		String str = "";
		for (int i = 0; i < digits; i++) {
			str += SOURCE.charAt(rand.nextInt(9));
		}
		return str;
	}
	
	private static final byte[] salt = "webplat".getBytes();

	public static void main(String[] args) {
	     String password = computeHash("interFACE123!@#");
	     System.out.println(password);
	     //System.out.println(randomDigit(8));
	     
	     
	}
	
}
